const Ajv = require("ajv")
const ajv = new Ajv({ allErrors: true, jsonPointers: true })
const localize = require('ajv-i18n')

//自定义错误
require('ajv-errors')(ajv)
// 自定义format
ajv.addFormat('test', (data) => {
  console.log(data, '-----------')
  return data === 'hahah'
})
// 自定义关键字
ajv.addKeyword('test', {
  // 方法一
  /*  validate (schema, data) {
     // console.log(schema, data)
     if (schema === true) return true
     return data.length === 6
   } */
  //方法二
  /*  compile (sch, parentSchema) {
     console.log(sch, parentSchema)
     return () => true
   } */
  // 方法三
  /* metaSchema: {
    type: 'boolean'
  } */
  //方法四
  macro () {
    return {
      minLength: 10
    }
  }
})
const schema = {
  type: "object",
  properties: {
    name: {
      type: 'string',

      //format: 'test'
      //test: false,
      /* errorMessage: {
        type: '必须是字符串',
        minLength: '长度不能小于10'
      }, */
      minLength: 10,
    },
    age: {
      type: 'number',
    },
    pets: {
      type: 'array',
      items: [
        {
          type: 'string',
          maxLength: 1
        },
        {
          type: 'number',
        },
      ]
    },
    isWorker: {
      type: 'boolean',
    }
  },
  required: ["name"],
  additionalProperties: false
}

const validate = ajv.compile(schema)

const data = {
  name: 'hahah',
  age: 18,
  pets: ['mini', 18],
  isWorker: true,
}

const valid = validate(data)
if (!valid) {
  localize.zh(validate.errors)
  console.log(validate.errors)
} 